package org.jeecg.modules.caiGgl.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.JsonUtils;
import org.jeecg.modules.caiGgl.entity.HqCggl;
import org.jeecg.modules.caiGgl.mapper.HqCgglMapper;
import org.jeecg.modules.caiGgl.service.IHqCgglService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 采购管理
 * @Author: jeecg-boot
 * @Date:   2020-06-17
 * @Version: V1.0
 */
@Service
public class HqCgglServiceImpl extends ServiceImpl<HqCgglMapper, HqCggl> implements IHqCgglService {

    @Autowired
    private IdentityService identityservice;
    @Autowired
    private RuntimeService runtimeservice;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public IPage<HqCggl> myApplyList(Page<HqCggl> page, LoginUser user, HqCggl hqCggl) {
        return this.baseMapper.myApplyList(page,user,hqCggl);
    }

    @Override
    public IPage<HqCggl> myTodoTasks(Page<HqCggl> page, LoginUser user, HqCggl hqCggl) {
        return this.baseMapper.myTodoTasks(page,user,hqCggl);
    }

    @Override
    public IPage<HqCggl> myDoneTasks(Page<HqCggl> page, LoginUser user, HqCggl hqCggl) {
        return this.baseMapper.myDoneTasks(page,user,hqCggl);
    }

    @Override
    @Transactional
    public void startFlow(HqCggl hqCggl, LoginUser loginUser) {
        List<SysUser> shenpiren = sysUserService.queryByPost(loginUser.getOrgCode(),"shenpiren");
        if(CollectionUtils.isEmpty(shenpiren)) {
            throw new RuntimeException("当前部门审批人为空");
        }

        String businesskey = "" + hqCggl.getId();

        identityservice.setAuthenticatedUserId(loginUser.getUsername());

        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("applyUser", loginUser.getUsername());
        variables.put("auditUser", shenpiren.get(0).getUsername());
        // 校级或院级分支标记 1校级 2院级
        variables.put("branch_baozqd", hqCggl.getBaozqd());

        Model modelData = repositoryService.getModel(hqCggl.getWorkFlowId());
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(modelData.getDeploymentId()).singleResult();

        ProcessInstance instance=runtimeservice.startProcessInstanceById(processDefinition.getId(),businesskey,variables);
        String instanceid=instance.getId();
        hqCggl.setProcessInstanceId(instanceid);
        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).taskAssignee(loginUser.getUsername()).singleResult();

        hqCggl.setTaskId(task.getId());

        this.baseMapper.updateById(hqCggl);

        taskService.complete(task.getId(),variables);
    }

    @Override
    public void complateTask(LoginUser loginUser, String taskId, String processInstanceId, Integer status, String memo, String auditUser) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        Map params = new HashMap() {{
            put("status",status);
            put("memo",memo);

            if(auditUser != null) {
                put("auditUser", auditUser);
                runtimeservice.setVariable(task.getExecutionId(),"auditUser",auditUser);
            }
        }};

        taskService.addComment(taskId, task.getProcessInstanceId(), JsonUtils.toJsonString(params));
        taskService.complete(taskId,params);
    }

    @Override
    public void applyAgain(HqCggl hqCggl, LoginUser user) {
        List<SysUser> shenpiren = sysUserService.queryByPost(user.getOrgCode(),"shenpiren");

        Task task = taskService.createTaskQuery().processInstanceId(
                hqCggl.getProcessInstanceId()).taskAssignee(user.getUsername()).singleResult();

        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("status", null);
        variables.put("auditUser",shenpiren.get(0).getUsername());
        taskService.complete(task.getId(),variables);
    }

    @Override
    public List<Map<String, Object>> jisCaigzxl(String startDate, String endDate) {
        return this.baseMapper.jisCaigzxl(startDate, endDate);
    }
}
